<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <a-col :md="6" :sm="8">
              <a-form-item :label="$t('message.Name_of_emission_source')+':'">
                <a-input v-model="queryParam.emissionSourceName" :placeholder="$t('message.Please_enter')" allowClear></a-input>
              </a-form-item>
            </a-col>

          <a-col :md="4" :sm="6">
              <a-form-item :label="$t('message.Accounting_year')+':'">
                <a-date-picker :placeholder="$t('message.Please_enter')" v-model="queryParam.year" allowClear :format="yearFormat" :valueFormat="yearFormat" mode="year" :open="yearOpen" @panelChange="opanelChange" @openChange="onopenelChange"/>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
                <a-form-item :label="$t('message.Accounting_entity')+':'">
                  <a-select
                    showSearch allowClear
                      style="width: 100%"
                      v-model="queryParam.targetId">
                    <a-select-option
                        v-for="province in CostCalcArr"
                        :key="province.id"
                        :value="province.id"
                    >
                      {{ province.departName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('message.Accounting_standard')+':'">
                <a-select showSearch allowClear style="width: 100%" v-model="queryParam.calculationCode" @change="calculationChange">
                    <a-select-option v-for="item in standardList" :key="item.code" :value="item.code" :label="item.title">
                      {{ item.title }}
                    </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('message.Scope_classification')+':'">
                <a-select showSearch allowClear style="width: 100%" v-model="queryParam.categoryId">
                  <a-select-opt-group v-for="item in ScopeClassification" :key="item.key" :value="item.key" :label="item.title">
                    <a-select-option v-for="item in item.children" :key="item.key" :value="item.key" :label="item.title">
                      {{ item.title }}
                    </a-select-option>
                  </a-select-opt-group>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('message.facilities_activities')+':'">
                <a-select
                showSearch allowClear
                      style="width: 100%"
                      v-model="queryParam.machineId">
                    <a-select-option
                        v-for="activity in activeityArr"
                        :key="activity.id"
                        :value="activity.id">
                      {{ activity.name }}
                    </a-select-option>
                  </a-select>
              </a-form-item>
            </a-col>

            <span  class="table-page-search-submitButtons">
              <a-col :md="6" :sm="24">
                <a-button type="primary" @click="searchQuery">{{$t('message.Search')}}</a-button>
                <a-button style="margin-left: 8px" @click="searchReset">{{$t('message.Reset')}}</a-button>
              </a-col>
            </span>


        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>

    <!-- table区域-begin -->
    <div>

      <a-tabs default-active-key="1" @change="callback">
        <a-tab-pane key="1" :tab="$t('message.Pending_data') +'(' + recordCountObject.pendingCount +')'"> </a-tab-pane>    
        <a-tab-pane key="2" :tab="$t('message.all_data') +'(' + recordCountObject.finishedCount +')'"> </a-tab-pane>
      </a-tabs>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange">


        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <template slot="carbonData" slot-scope="text,record">
          {{record.carbonData}}  {{record.carbonMolecule}}/{{record.carbonDenomintor}}
        </template>

        <template slot="emissionAmountSlot" slot-scope="text,record">
          {{record.emissionAmount}} {{record.carbonMolecule}}
        </template>

        <template slot="targetName" slot-scope="text,record">
          {{record.targetName}} | {{record.year}}
        </template>

        <template slot="dataSlot" slot-scope="text,record">
          <div v-if="record.status == 1">
            <a-input v-model="record.data"  style="width: 60px; text-align: center " ></a-input> {{record.dataUnitText}}
          </div>

          <div v-else>
            <a-input  v-model="record.data"  style="width: 60px; text-align: center " disabled></a-input> {{record.dataUnitText}}
          </div>
        </template>

        <template slot="datavoucherSlot" slot-scope="text,record">
            <j-upload v-model="record.dataVoucher" :number="3" style="max-width: 100px" :disabled="true"></j-upload>
        </template>

        <span slot="action" slot-scope="text, record">
          <div style="display: flex; align-items: center;justify-content: center">
            <j-upload v-if="record.status == 1" v-model="record.dataVoucher" :buttonVisible="false" :showUploadList="false" :number="1" style="max-width: 100px"></j-upload>
            <a-divider v-if="record.status == 1"  type="vertical" />
            <a v-if="record.status == 1"  @click="toEdit(record)">{{$t('message.submit')}}</a>
            <a v-else @click="openEditModel(record)">{{$t('message.modify')}}</a>
          </div>
        </span>

      </a-table>
    </div>

    <cy-invitation-fill-in-modal ref="modalForm" @ok="modalFormOk"></cy-invitation-fill-in-modal>

    <a-modal
      :title="$t('message.modify')"
      :visible="editModelVisible"
      @ok="handleOk"
      @cancel="handleCancel">


      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-item :label="$t('message.Active_data')+':'">
              <a-input v-model="currentEditObject.data" style="width: 60px; text-align: center " ></a-input> {{currentEditObject.dataUnitText}}
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="8">
            <a-form-item :label="$t('message.Datavoucher')+':'">
              <j-upload v-model="currentEditObject.dataVoucher" :number="1" style="max-width: 100px"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import CyInvitationFillInModal from './modules/CyInvitationFillInModal'
import { getAction,postAction } from '../../../api/manage'
import moment from "moment";

  export default {
    name: 'CyInvitationFillInList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      CyInvitationFillInModal
    },
    data () {
      return {
        description: '邀请填报碳盘查数据管理页面',
        // 表头
        columns: [
          {
            title: this.$t('message.Accounting_entity'),
            align:"center",
            dataIndex: 'targetName',
            scopedSlots: { customRender: 'targetName' }
          },
          {
            title: this.$t('message.Accounting_standard'),
            align:"center",
            dataIndex: 'categoryId_dictText'
          },
          {
            title: this.$t('message.Scope_classification'),
            align:"center",
            dataIndex: 'standardId_dictText'
          },
          {
            title: this.$t('message.Emission_source'),
            align:"center",
            dataIndex: 'emissionSourceName'
          },
          {
            title: this.$t('message.Active_data'),
            align:"center",
            dataIndex: 'data',
            scopedSlots: { customRender: 'dataSlot' }
          },
          {
            title: this.$t('message.Datavoucher'),
            align:"center",
            dataIndex: 'dataVoucher',
            scopedSlots: { customRender: 'fileSlot' }
          },
          {
            title: this.$t('message.Emission_factor_values'),
            align:"center",
            dataIndex: 'carbonData',
            scopedSlots: { customRender: 'carbonData' }
          },
          {
            title: this.$t('message.activity/facilities'),
            align:"center",
            dataIndex: 'activitieId_dictText'
          },
          {
            title: this.$t('message.Inviter'),
            align:"center",
            dataIndex: 'username'
          },
          {
            title: this.$t('message.Emissions'),
            align:"center",
            dataIndex: 'emissionAmount',
            scopedSlots: { customRender: 'emissionAmountSlot' }
          },
          {
            title: this.$t('message.Invitation_time'),
            align:"center",
            dataIndex: 'inviteTime'
          },
          {
            title: this.$t('message.Update_date'),
            align:"center",
            dataIndex: 'updateTime'
          },
          {
            title: this.$t('message.Handle'),
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }


        ],
        url: {
          list: "/CyInvitationFillIn/cyInvitationFillIn/list",
          delete: "/CyInvitationFillIn/cyInvitationFillIn/delete",
          deleteBatch: "/CyInvitationFillIn/cyInvitationFillIn/deleteBatch",
          exportXlsUrl: "/CyInvitationFillIn/cyInvitationFillIn/exportXls",
          importExcelUrl: "CyInvitationFillIn/cyInvitationFillIn/importExcel",
          edit: "/CyInvitationFillIn/cyInvitationFillIn/edit"
        },
        dictOptions:{},
        superFieldList:[],
        provinceData:[],
        queryParam:{
          status : 1,
          machineId: undefined,
          targetId: undefined
        },
        disableFlag : false,
        editModelVisible: false,
        currentEditObject: {},
        yearFormat: 'YYYY',
        yearOpen: false,
        // 核算主体列表
        CostCalcArr: [],
        // 活动设施列表
        activeityArr: [],
        // 范围分类列表
        ScopeClassification: [],
        // 核算标准
        standardList: [],
        // 统计数据对象
        recordCountObject: {}
      }
    },
    created() {
    this.getSuperFieldList();
    // 查询核算主体
    this.OfCostCalcSaveUpdate();
    // 查询活动设施
    this.getAllActivity();
    // 查询范围分类
    // this.getTree();
    // 查询核算标准
    this.getStandard();
    // 查询记录统计数
    this.getRecordCount();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      /**
       * 查询记录统计数
       */
      getRecordCount(){
        getAction("/CyInvitationFillIn/cyInvitationFillIn/countRecord").then((res) => {
          this.recordCountObject = res.result;
        })
      },
      calculationChange(e){
        this.standardList.forEach(item => {
          if(item.code == e){
            this.$set(this.queryParam, 'calculationCode', item.code)
            this.getTree(this.queryParam.calculationCode);
            this.queryParam.categoryId = null
          }
        })
      },
      /**
       * 查询核算标准
       */
      getStandard(){
        getAction("/sys/category/loadTreeRoot", {
        pcode: "A01",
        async: false,
      }).then((res) => {
        this.standardList = res.result
        // 默认选择第一个核算标准
        this.queryParam.calculationCode = this.standardList[0].code
        this.getTree(this.queryParam.calculationCode);
      });
      },
      /**
       * 查询所有范围分类
       */
      getTree(code){
        getAction("/sys/category/loadTreeRoot", {
        pcode: code,
        async: false,
      }).then((res) => {
        this.ScopeClassification = res.result
      });
      },
      /**
       * 查询所有活动设施
       */
       getAllActivity() {
        getAction("/orgActivitie/getAll").then((res) => {
          if (res.success) {
            this.activeityArr = res.result
          }
        });
      },
      /**
       * 核算主体
       */
      OfCostCalcSaveUpdate() {
        getAction("/orgDept/getOrgAllSubjectOfCostCalc", {
          name: "",
        }).then((res) => {
          if (res.success) {
            this.CostCalcArr = res.result;
          }
        });
      },
      /**
       *时间选择
      */
      onopenelChange(status) {
        this.yearOpen = status;
      },
      opanelChange(value, mode) {
        console.log(value, mode);
        this.queryParam.year = moment(value).format("YYYY");
        this.yearOpen = false;
      },
      searchReset(){
        let status = this.queryParam.status
        this.queryParam = {
          emissionSourceName: undefined,
          year: undefined,
          machineId: undefined,
          targetId: undefined,
          calculationCode: undefined,
          categoryId: undefined
        }
        this.queryParam.status = status;
        this.ScopeClassification = []
        this.searchQuery();
      },
      toEdit(record){
        postAction(this.url.edit,record).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
        }
      });
      this.queryParam.status = 1;
      this.searchQuery();
      },
      /**
       * 打开修改对话框
       * @param record
       */
      openEditModel(record){
        if(record.accountingStatus == 1){
          this.$message.error('当前核算已归档，无法修改');
          return
        }
        this.editModelVisible = true;
        this.currentEditObject = record;
      },
      handleCancel(){
        this.editModelVisible = false;
      },
      handleOk(){
      this.editModelVisible = false;
      postAction(this.url.edit,this.currentEditObject).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
        }
      });
      this.queryParam.status = 2;
      this.searchQuery();

      },
        /**
       * 切换状态选项事件
       * @param key
       */
      callback(key){
        this.queryParam.status = key;
        this.searchQuery();
        this.getRecordCount();
      },
      /**
     * 核算标准
     */
     loadTreeRoot(value) {
      console.log(value);
      getAction("/sys/category/loadTreeRoot", {
        pcode: "A01",
        async: true,
      }).then((res) => {
        if (res.success) {
          this.provinceData = res.result;
        }
      });
    },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'checkId',text:'盘查id',dictCode:''})
        fieldList.push({type:'string',value:'checkDetailId',text:'碳盘查详情id',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'data',text:'活动数据',dictCode:''})
        fieldList.push({type:'string',value:'organizationId',text:'组织id',dictCode:''})
        fieldList.push({type:'string',value:'deptId',text:'部门ID',dictCode:''})
        fieldList.push({type:'string',value:'userId',text:'填报人id',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

</style>
